<script setup lang="ts">
import { ColumnsType } from 'ant-design-vue/es/table';
import { h } from 'vue'
const antIcons: any = inject('antIcons')
import { getFilePageApi, deleteFilesApi } from '@/api/file'
import { SysFile, R } from '@/interface/user';
import { UploadChangeParam, message } from 'ant-design-vue';
import Cookies from 'js-cookie'
import {
  CopyOutlined
} from '@ant-design/icons-vue'
import { Key } from 'ant-design-vue/es/table/interface';
import { Page } from '@/interface/log'
import copy from 'copy-to-clipboard'
import { pathRewrite } from '@/utils/request'
import { useUserStore } from '@/store/userStore';
import { useGlobalStore } from '@/store/globalStore';
import { getAssetsImage } from '@/utils/jsUtil'
import { ValueType } from 'ant-design-vue/es/input-number/src/utils/MiniDecimal';

const columns: ColumnsType<any> = [
  {
    title: '/',
    dataIndex: 'id',
    customRender: ({ index }) => {
      return `${index + 1}`;
    },
    width: 50,
  },
  {
    title: '浏览图',
    key: 'image',
    dataIndex: 'image',
    width: 100,
  },
  {
    title: '文件地址',
    dataIndex: 'fileUrl',
    key: 'fileUrl',
  },
  {
    title: '文件类型',
    dataIndex: 'fileType',
    key: 'fileType',
    width: 150,
    ellipsis: true,
  },
  {
    title: '文件大小',
    dataIndex: 'fileSize',
    key: 'fileSize',
    width: 100,
    customRender: ({ text }) => {
      return `${text}MB`
    }
  },
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    width: 150,
    ellipsis: true,
  },
  {
    title: '上传日期',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 160,
  },
  {
    title: '创建者',
    dataIndex: 'createBy',
    key: 'createBy',
    ellipsis: true,
    width: 100,
  },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    width: 100,
  },
];

const userStore = useUserStore();
const globalStore = useGlobalStore()
const data = ref<SysFile[]>([])
const fileList = ref([])

const contentBoxRef = ref<HTMLElement>()
const currentPage = ref<number>(1);
const size = ref<number>(10);
const total = ref<number>(0);
const isLoading = ref<boolean>(false);
const searchObj = reactive({
  fileName: '',
  fileSize: undefined as ValueType | undefined,
  fileType: '',
})

const tableStyle = reactive<{
  width: number,
  height: number
}>({
  width: 300,
  height: 300
})

const getFiles = async (isSearch = false) => {
  isLoading.value = true;
  data.value = []
  if (isSearch) {
    pageChanged(1, size.value)
    return
  }
  try {
    const { data: res }: { data: R<Page<SysFile[]>> } =
      await getFilePageApi(currentPage.value, size.value, searchObj.fileName, searchObj.fileType, searchObj.fileSize || -1)
    currentPage.value = res.data.current
    size.value = res.data.size
    total.value = res.data.total
    //key用于选中操作
    data.value = res.data.records.map((item: any) => {
      item.key = item.id
      return item
    })
  } catch (error) {

  } finally {
    isLoading.value = false;
  }
}

const pageChanged = (page: number, pageSize: number) => {
  currentPage.value = page
  size.value = pageSize
  getFiles()
}

const reloadData = () => {
  getFiles()
}

const resetData = () => {
  searchObj.fileName = ''
  searchObj.fileSize = undefined
  searchObj.fileType = ''
  pageChanged(1, 10)
}

const deleteData = async (_e: MouseEvent, fileId: number) => {
  return new Promise((resolve) => {
    deleteFilesApi(fileId.toString()).then(res => {
      if (res.data.code == 200) {
        message.success('删除成功')
        reloadData()
      } else {
        message.error(res.data.msg || '删除失败')
      }
      resolve(true)
    })
  });
}

const deleteBatchData = async () => {
  deleteFilesApi(selectedRows.value.join(',')).then(res => {
    if (res.data.code == 200) {
      message.success('删除成功')
      selectedRows.value = []
    } else {
      message.error(res.data.msg || '删除失败')
    }
    getFiles()
  })
}

//当前选中行
const selectedRows = ref<Key[]>([])
const onSelectChange = (selectedRowKeys: Key[]) => {
  selectedRows.value = selectedRowKeys;
};

const addPopShow = ref(false)

const handleAddData = () => {
  addPopShow.value = true
}

const copyFileUrl = (fileUrl: string) => {
  let ok = copy(fileUrl)
  if (ok) {
    message.success('复制成功')
  }
}

const beforeUpload = (file: any) => {
  const isLt64M = file.size / 1024 / 1024 < 64;
  if (!isLt64M) {
    message.error('大小必须小于64MB!');
  }
  return isLt64M;
};

const uploadImgLoading = ref(false)
const handleChange = async (info: UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    uploadImgLoading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    uploadImgLoading.value = false;
    let response = info.file.response;
    if (response.code === 200) {
      message.success('上传成功');
      reloadData()
    } else {
      message.error(response.msg || '上传失败')
    }
  }
  if (info.file.status === 'error') {
    uploadImgLoading.value = false;
    message.error('上传失败');
  }
};

onMounted(() => {
  getFiles()
  tableStyle.height = contentBoxRef.value?.clientHeight as number - 200
  tableStyle.width = contentBoxRef.value?.clientWidth as number
})
</script>
<template>
  <div class="box-border relative w-full h-full p-6" ref="contentBoxRef"
    :style="{ width: globalStore.isMobile ? 'calc(100% - 60px)' : '100%' }">
    <a-row>
      <a-col :span="24">
        <a-space class="flex">
          <a-upload v-model:file-list="fileList" name="file" list-type="picture" :show-upload-list="false"
            :action="`${pathRewrite}/sys/file/manage/add`" :before-upload="beforeUpload" @change="handleChange"
            :max-count="50" :headers="{
      'Authorization': userStore.accessToken || Cookies.get('accessToken') || ''
    }" multiple>
            <a-button type="ghost"
              class="flex items-center text-white bg-green-500 hover:bg-green-400 hover:border-green-400 "
              :icon="h(antIcons['UploadOutlined'])" @click="handleAddData" :loading="uploadImgLoading">上传文件</a-button>
          </a-upload>
          <a-input placeholder="文件名" class="w-[160px]" v-model:value="searchObj.fileName"
            @keydown.enter="getFiles(true)" />
          <a-input placeholder="文件类型" class="w-[160px]" v-model:value="searchObj.fileType"
            @keydown.enter="getFiles(true)" />
          <a-input-number placeholder="最大文件容量(MB)" class="w-[160px]" :max="64" :min="-1"
            v-model:value="searchObj.fileSize" @keydown.enter="getFiles(true)" addon-after="MB" />
          <a-button type="primary" class="flex items-center bg-primary-2" :icon="h(antIcons['SearchOutlined'])"
            @click="getFiles(true)" :loading="isLoading">查询</a-button>
          <a-button class="flex items-center" :icon="h(antIcons['ReloadOutlined'])" @click="resetData">重置</a-button>
          <a-button class="flex items-center justify-center" :icon="h(antIcons['ReloadOutlined'])" shape="circle"
            @click="reloadData"></a-button>
          <a-button type="primary" class="flex items-center" danger :icon="h(antIcons['CloseOutlined'])"
            :disabled="selectedRows.length == 0" @click="deleteBatchData">删除</a-button>
        </a-space>
      </a-col>
    </a-row>
    <!-- 表格 -->
    <div class="mt-3  h-fit max-h-[647px]">
      <a-table :columns="columns" :data-source="data" :pagination="false" :loading="isLoading"
        :scroll="{ y: tableStyle.height, x: globalStore.isMobile ? 'calc(100% + 800px)' : '100%' }"
        :row-selection="{ selectedRowKeys: selectedRows, onChange: onSelectChange }">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'operation'">
            <a-space>
              <a-popconfirm :title="`确定删除这个文件吗?`" ok-text="确认" cancel-text="取消" :okButtonProps="{ type: 'default' }"
                @confirm="deleteData($event, text.id)">
                <!-- <template #okButton>
                  <a-button size="small" type="primary" class="bg-primary-2" @click="deleteData(text.userId)">确认</a-button>
                </template> -->
                <a-button size="small" type="primary" danger class="flex items-center text-white ">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
          <template v-if="column.key === 'image'">
            <img v-if="record.fileName.substring(record.fileName.lastIndexOf('.')) === '.mp3'"
              :src="getAssetsImage(globalStore.darkMode === '0' ? 'music.png' : 'dark-music.png')" alt="">
            <video v-else-if="record.fileType.includes('video')" :src="record.fileUrl"></video>
            <img v-else-if="record.fileType.includes('image')" class="object-cover rounded-lg w-fit"
              :src="record && record.fileUrl ? record.fileUrl : 'https://gw.alipayobjects.com/zos/antfinc/efFD%24d%29/KDNkMl7GN.png'">
            <img v-else-if="record.fileName.substring(record.fileName.lastIndexOf('.')) === '.md'"
              :src="getAssetsImage(globalStore.darkMode === '0' ? 'MD.png' : 'dark-MD.png')" alt="">
            <img v-else-if="record.fileType.includes('word')"
              :src="getAssetsImage(globalStore.darkMode === '0' ? 'word.png' : 'dark-word.png')" alt="">
            <img v-else-if="record.fileType.includes('pdf')"
              :src="getAssetsImage(globalStore.darkMode === '0' ? 'format-pdf.png' : 'dark-format-pdf.png')" alt="">
            <img v-else :src="getAssetsImage(globalStore.darkMode === '0' ? 'file.png' : 'dark-file.png')" alt="">
          </template>
          <template v-if="column.key === 'fileUrl'">
            <div class="flex min-w-[50px]">
              <CopyOutlined class="mr-2 cursor-pointer" @click="copyFileUrl(record.fileUrl)" />
              <a-tooltip placement="top">
                <template #title>
                  <p>{{ record.fileUrl || '' }}</p>
                </template>
                <a :href="record.fileUrl" class="w-full select-none line-clamp-1" target="_blank">{{ record.fileUrl ||
      ''
                  }}</a>
              </a-tooltip>
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <div
      class="absolute bottom-0 left-0 right-0 p-3 mt-3 bg-white border-t-[1px] z-10 dark:bg-darkBg dark:border-gray-600">
      <a-pagination v-model:current="currentPage" v-model:page-size="size" :total="total"
        :show-total="total => `总共 ${total} 条`" show-size-changer @change="pageChanged" />
    </div>
  </div>
</template>

<style scoped></style>